import axios from "axios"
import { proxyReplace } from "./proxyReplace"
import userInfoStore from "@/store/userInfo/index"
import { createElement, removeElement } from "@/components/spinLoading/destoryControl"
import { messageApi } from "@/utils/messageService"
// 超时时间
const SECOND = 10
const MILL_SECOND = 1000
let ajaxCount = 0

class Http {
  constructor() {
    this.instance = this._setupAxios()
    this.navigate = null
  }
  _setupAxios() {
    const instance = axios.create({
      withCredentials: true,
      timeout: MILL_SECOND * SECOND
    })

    instance.interceptors.request.use(this._requestInterceptor.bind(this), (error) =>
      Promise.reject(error)
    )

    instance.interceptors.response.use(
      this._responseInterceptor.bind(this),
      this._errorInterceptor.bind(this)
    )

    return instance
  }

  _requestInterceptor(config) {
    createElement()
    ajaxCount++
    const { getToken } = userInfoStore.getState()
    config.url && (config.url = proxyReplace(config.url))
    config.headers["Authorization"] = getToken() || ""

    // 解决get请求缓存问题
    if (config.method && config.method.toLowerCase() === "get") {
      config.params = {
        ...config.params,
        // 增加接口时间戳
        t_t: new Date().getTime()
      }
    }
    return config
  }

  _responseInterceptor(response) {
    removeElement()
    ajaxCount && ajaxCount--
    const { status, data } = response
    if (status === 200) {
      return Promise.resolve(data)
    } else {
      !ajaxCount && messageApi.error(data.msg || "请求信息错误")
      return
    }
  }

  _errorInterceptor(error) {
    const { updateInfo } = userInfoStore.getState()
    removeElement()
    ajaxCount && ajaxCount--
    if (error.response) {
      let msg
      switch (error.response.status) {
        case 401:
          msg = "登录已过期，请重新登录！"
          updateInfo({})
          this.navigate("/login", { replace: true })
          break
        case 404:
          msg = "接口请求不存在!错误码【404】。"
          break
        case 500:
          msg = error.response.data.message || "服务端应用接口异常!错误码【500】。"
          break
        default:
          msg = "请求错误，请检查或刷新重试！"
          break
      }
      !ajaxCount && messageApi.error(msg)
    } else {
      !ajaxCount && messageApi.error("服务不可用")
    }
    return Promise.reject(error)
  }
  // 新增方法，用于设置navigate函数
  setNavigate(navigate) {
    this.navigate = navigate
  }

  get(url, params, isVerify = false) {
    const annotation = {}
    isVerify && (annotation.isVerify = isVerify)
    return this.instance.get(url, { params, annotation })
  }

  post(url, data, isVerify = false, isFormData = false) {
    const annotation = {}
    isVerify && (annotation.isVerify = isVerify)
    return this.instance.post(url, data, {
      annotation,
      headers: { "Content-Type": isFormData ? "multipart/form-data" : "application/json" }
    })
  }

  // 获取实例
  getInstance() {
    return this.instance
  }
}

const http = new Http()
export default http
